package com.csweimei.rentmanagementtreasure.tenant.viewModel;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.app.Application;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.csweimei.rentmanagementtreasure.R;
import com.csweimei.rentmanagementtreasure.base.AppConfig;
import com.csweimei.rentmanagementtreasure.http.Repository;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.http.entity.CustomerDetailBean;
import com.csweimei.rentmanagementtreasure.http.entity.QuarterEntity;
import com.csweimei.rentmanagementtreasure.http.postBean.PostCustomerBean;
import com.csweimei.rentmanagementtreasure.pop.PopArea;
import com.csweimei.rentmanagementtreasure.pop.PopBean;
import com.csweimei.rentmanagementtreasure.pop.PopIntention;
import com.csweimei.rentmanagementtreasure.pop.PopMonthRent;
import com.csweimei.rentmanagementtreasure.pop.PopQuarters;
import com.csweimei.rentmanagementtreasure.pop.PopSelClick;
import com.csweimei.rentmanagementtreasure.pop.PopUtils;
import com.csweimei.rentmanagementtreasure.utils.DialogUtils;
import com.csweimei.rentmanagementtreasure.utils.GlideEngine;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.utils.permission.RxPermissionsUtils;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunBean;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUpload;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUploadCallBack;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gtdev5.geetolsdk.mylibrary.util.GsonUtils;
import com.gtdev5.geetolsdk.mylibrary.util.LogUtils;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AddCustomerVM extends TitleVM {

    public ObservableField<PostCustomerBean> customerBean = new ObservableField<>(new PostCustomerBean());

    public ObservableField<String> birthday = new ObservableField<>();
    public ObservableField<String> customImg = new ObservableField<>();
    public ObservableField<String> imgs = new ObservableField<>();

    public ObservableField<String> rent = new ObservableField<>();

    public ObservableField<String> area = new ObservableField<>();

    public ObservableField<String> quarters = new ObservableField<>();
    public ObservableField<String> details = new ObservableField<>();

    public ObservableField<String> type = new ObservableField<>();

    public AddCustomerVM(Application mApplication, Repository mRepository) {
        super(mApplication, mRepository);
    }


    public void getCustomerData(String id) {
        Map<String,String> map = AppConfig.getCurMap(model);
        map.put("sid",id);
        model.customdetails(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<CustomerDetailBean>() {
                    @Override
                    public void onNext(CustomerDetailBean o) {
                        if (o.issucc){
                            setViewValue(o.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void setViewValue(CustomerDetailBean.DataDTO data) {
        customImg.set(data.getCustomImg());

        PostCustomerBean postCustomerBean = new PostCustomerBean();
        postCustomerBean.sid = data.getId()+"";
        postCustomerBean.customImg = data.getCustomImg();
        postCustomerBean.name = data.getName();
        postCustomerBean.sex = data.getSex();
        postCustomerBean.phone = data.getPhone();
        postCustomerBean.WeChat = data.getWeChat();
        postCustomerBean.birthday = data.getBirthday();
        postCustomerBean.IDCard = data.getIDCard();
        postCustomerBean.customType = data.getCustomType();

        postCustomerBean.minRent = data.getMinRent();
        postCustomerBean.maxRent = data.getMaxRent();
        if (ValidateUtils.isNotEmptyString(data.getMinRent())){
            rent.set(data.getRent());
        }
        postCustomerBean.minArea = data.getMinArea();

        postCustomerBean.maxArea = data.getMaxArea();
        if (ValidateUtils.isNotEmptyString(data.getMinArea())){
            area.set(data.getArea());

        }

        postCustomerBean.quarters = data.getQuarters();
        quarters.set(data.getQuarters());
        postCustomerBean.details = data.getDetails();
        details.set(data.getDetails());
        postCustomerBean.notes = data.getNotes();
        customerBean.set(postCustomerBean);
    }

    public BindingCommand timeSel  = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            TimePickerView pvTime = new TimePickerBuilder(mActivity, (date, v) -> {
                birthday.set(new SimpleDateFormat("yyyy-MM-dd").format(date));
                customerBean.get().setBirthday(birthday.get());
            })
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("年", "月", "日", "", "", null)
                    .build();
            pvTime.show();
        }
    });
    public BindingCommand imgSel = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            RxPermissionsUtils.file(mActivity, (RxPermissionsUtils.Accept) () -> {
                PictureSelector.create(mActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .isDisplayCamera(false)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)
                        .setMinSelectNum(1)
                        .setImageSpanCount(4)
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                imgs.set(result.get(0).getRealPath());
                                getQNYToken();
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            });
        }
    });

    public BindingCommand rentClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            PopMonthRent popMonthRent = new PopMonthRent(mActivity,
                    Arrays.asList(mActivity.getResources().getStringArray(R.array.rentList)),
                    x -> {
                        customerBean.get().minRent = x.getName().split("-")[0];
                        customerBean.get().maxRent = x.getName().split("-")[1];
                        rent.set(x.getName());
                    });
            PopUtils.showPop(mActivity,popMonthRent,true);
        }
    });

    public BindingCommand areaClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            PopArea popArea = new PopArea(mActivity,
                    Arrays.asList(mActivity.getResources().getStringArray(R.array.areaList)),
                    x -> {
                        customerBean.get().minArea = x.getName().split("-")[0];
                        customerBean.get().maxArea = x.getName().split("-")[1];
                area.set(x.getName());

            });
            PopUtils.showPop(mActivity,popArea,false);
        }
    });

    public BindingCommand xqClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getQuartersData();
        }
    });

    private void getQuartersData() {
        Map<String,String> map = new HashMap<>();
        map.put("userid",model.getLoginInfo().getData().getUser_id());
        model.get_quarters(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QuarterEntity>() {
                    @Override
                    public void onNext(QuarterEntity bean) {
                        if (bean.issucc){
                            showPop(bean.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void showPop(List<QuarterEntity.DataDTO> data) {
        PopQuarters popQuarters = new PopQuarters(mActivity, data,new PopSelClick() {
            @Override
            public void sel(PopBean x) {
                if (x.getName().contains("&&")){
                    addQuarters(x.getName());
                }else {
                    quarters.set(x.getName());
                    customerBean.get().quarters = quarters.get();
                }
            }
        });
        PopUtils.showPop(mActivity,popQuarters,false);

    }

    /**
     * 添加小区
     */
    private void addQuarters(String add) {
        String[] s = add.split("&&");
        quarters.set(s[0]);
        customerBean.get().quarters = quarters.get();


        Map<String,String> map = new HashMap<>();
        map.put("userid",model.getLoginInfo().getData().getUser_id());

        map.put("village",s[0]);
        map.put("city",s[1]);
        map.put("address",s[2]);

        model.add_quarters(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                    DialogUtils.showLoading(mActivity,"数据处理中");
                })
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult bean) {
                        DialogUtils.stopLoading();
                        if (bean.issucc){
                            ToastUtils.showShort(bean.msg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogUtils.stopLoading();
                    }

                    @Override
                    public void onComplete() {
                        DialogUtils.stopLoading();
                    }
                });

    }


    public BindingCommand yxClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            PopIntention popIntention = new PopIntention(mActivity, new PopSelClick() {
                @Override
                public void sel(PopBean x) {
                    String[] strings =x.getName().split("-");
                    details.set("户型:"+strings[0]+"朝向:"+strings[1]+"其他:"+strings[2]);
                    customerBean.get().details = details.get();
                }
            });

            PopUtils.showPop(mActivity,popIntention,false);
        }
    });


    /**
     * 获取七牛云token
     */
    private void getQNYToken() {
        model.getToken()
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QiNiuYunBean>() {
                    @Override
                    public void onNext(QiNiuYunBean qiniuYunBean) {
                        if (ValidateUtils.isNotEmptyObjectOrString(qiniuYunBean) &&
                                ValidateUtils.isNotEmptyString(qiniuYunBean.getToken())) {
                            uploadQNY(qiniuYunBean.getToken());
                        } else {
                            ToastUtils.showShort( "请求失败，请联系管理员");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void uploadQNY(String token) {
        String suffix = imgs.get().substring( imgs.get().lastIndexOf("."));
        String key = "works/zgb/" + System.currentTimeMillis() + suffix;
        QiNiuYunUpload.uploadFileToQny(mActivity, imgs.get(), token, key, new QiNiuYunUploadCallBack() {
            @Override
            public void onSuccess(String url) {
                customImg.set(url);
                customerBean.get().customImg = url;

            }

            @Override
            public void onFail() {

            }

            @Override
            public void onProgress(String key, double progress) {

            }
        });

    }




    public BindingCommand saveData = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            LogUtils.e(customerBean.get().toString());

            if (ValidateUtils.isEmptyString(customImg.get())){
                ToastUtils.showShort("请选择客户图片");
                return;
            }

            if (ValidateUtils.isEmptyString(customerBean.get().name)){
                ToastUtils.showShort("请输入客户姓名");
                return;
            }

            if (ValidateUtils.isEmptyString(customerBean.get().phone)){
                ToastUtils.showShort("请输入客户电话");
                return;
            }

           postData();

        }
    });

    private void postData() {
        String postjson = GsonUtils.getStringFromBean(customerBean.get());
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> map1 = objectMapper.readValue(postjson, Map.class);
            map1.put("userid",model.getLoginInfo().getData().getUser_id());
            model.addcustom(map1)
                    .compose(RxUtils.schedulersTransformer())
                    .compose(RxUtils.exceptionTransformer())
                    .doOnSubscribe(this)
                    .doOnSubscribe(disposable -> {
                        DialogUtils.showLoading(mActivity);
                    })
                    .subscribe(new DisposableObserver<BaseResult>() {
                        @Override
                        public void onNext(BaseResult bean) {
                            DialogUtils.stopLoading();
                            if (bean.issucc){
                                finish();
                            }

                        }

                        @Override
                        public void onError(Throwable e) {
                            DialogUtils.stopLoading();
                        }

                        @Override
                        public void onComplete() {
                            DialogUtils.stopLoading();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            DialogUtils.stopLoading();
        }
    }
}

